package com.ysu.yybk.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.util.concurrent.RateLimiter;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.ysu.yybk.VO.login.LoginVO;
import com.ysu.yybk.client.WxLoginClient;
import com.ysu.yybk.dto.WxLoginDTO;
import com.ysu.yybk.entity.member.Student;
import com.ysu.yybk.mapper.member.StudentMapper;
import com.ysu.yybk.service.LoginService;
import com.ysu.yybk.util.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.List;

/**
 * @author ：lhw
 * @date ：Created in 2019/11/25 17:18
 */
@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    WxLoginClient wxLoginClient;

    @Autowired
    ObjectMapper objectMapper;

    @Autowired
    StudentMapper studentMapper;

    private static final RateLimiter rateLimiter = RateLimiter.create(2);

    @Override
    @HystrixCommand(fallbackMethod = "studentLoginFail",commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1500")
    })
    public LoginVO studentLogin(String code) {
//        boolean flag = rateLimiter.tryAcquire();
//        if(!flag){
//            LoginVO loginVO = new LoginVO();
//            loginVO.setErrorCode("10004");
//            return loginVO;
//        }
        String openidString = wxLoginClient.getStudentOpenId(code);

        WxLoginDTO wxLoginDTO = null;
        try {
            wxLoginDTO = objectMapper.readValue(openidString,WxLoginDTO.class);
        } catch (IOException e) {
            e.printStackTrace();
        }

        //获取openid失败
        if(wxLoginDTO == null || StringUtils.isEmpty(wxLoginDTO.getOpenid())){
            LoginVO loginVO = new LoginVO();
            loginVO.setErrorCode("10003");
            return loginVO;
        }

        List<Student> students = studentMapper.selectList(new QueryWrapper<Student>().eq("wx_id", wxLoginDTO.getOpenid()));

        //尚未绑定
        if(students.isEmpty() || students.size()>1){
            LoginVO loginVO = new LoginVO();
            loginVO.setErrorCode("20101");
            return loginVO;
        }

        LoginVO loginVO = new LoginVO();
        loginVO.setErrorCode("0");
        loginVO.setStudentId(students.get(0).getId());
        loginVO.setStudentName(students.get(0).getName());
        return loginVO;

    }

    public LoginVO studentLoginFail(String code){
        LoginVO loginVO = new LoginVO();
        loginVO.setErrorCode("10004");
        return loginVO;
    }
}
